<template>
  <!-- 计划批次表单弹窗 -->
  <el-dialog
    :close-on-click-modal="false"
    v-model="visibleDialog"
    :title="props.title"
    width="1100px"
    draggable
    @close="closeDialog"
  >
    <el-form ref="formRef" :model="tableData" :rules="rules" label-width="100">
      <!-- <el-row>
        <el-col :span="12">
          <el-form-item label="工厂" prop="plantId">
            <el-select
              v-if="!props.isReadonly"
              @change="plantChange"
              v-model="formData.plantId"
              :disabled="formData.id != ''"
              placeholder="请选择工厂"
              style="width: 100%"
            >
              <el-option
                v-for="item in plantList"
                :key="item.id"
                :label="item.organizationCode"
                :value="item.id"
              />
            </el-select>
            <span v-else>{{ formData.plantCode }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="计划年份" prop="planYear">
            <el-select
              v-model="formData.planYear"
              placeholder="请选择计划年份"
              clearable
              style="width: 100%"
            >
              <el-option
                v-for="item in yearOptions"
                :key="item"
                :value="Number(item)"
                :label="item"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row> -->
      <div style="display: flex; align-items: center" v-if="!props.isReadonly">
        <el-button type="primary" v-if="!props.isReadonly" @click="countSubmit">
          计算
        </el-button>
        <div class="mb-[10px] mt-[20px] ml-[20px] text-[15px]">
          {{
            `选择的卷料总重量为 ${
              props.number
            }，计算过重量合计为${sum}，剩余重量为${
              sum ? props.number - sum : 0
            }`
          }}
        </div>
      </div>
      <div class="formTable">
        <el-table
          ref="dataTableRef"
          v-loading="loading"
          :data="tableData"
          highlight-current-row
          border
          style="margin-top: 10px"
        >
          <el-table-column label="序号" width="60" align="center" type="index">
          </el-table-column>
          <el-table-column
            label="存货编码"
            prop="materialCode"
            min-width="120"
            show-overflow-tooltip
          >
          </el-table-column>
          <el-table-column
            label="图号"
            prop="figureNumber"
            min-width="160"
            show-overflow-tooltip
          >
          </el-table-column>
          <el-table-column
            label="卷料重量"
            prop="numberWeigth"
            min-width="120"
            show-overflow-tooltip
            align="center"
          >
            <template #default="{ $index, row }">
              <el-form-item
                :prop="$index + '.numberWeigth'"
                label-width="0"
                :rules="rules.numberWeigth"
              >
                <el-input
                  v-model="row.numberWeigth"
                  placeholder="请输入"
                  clearable
                  small
                />
              </el-form-item>
            </template>
          </el-table-column>

          <el-table-column
            label="单位"
            prop="quantityUnit"
            min-width="60"
            show-overflow-tooltip
          >
            <template #default="{ $index, row }">
              {{ useDictionary("MeasurementUnit", row.quantityUnit) }}
            </template>
          </el-table-column>
          <el-table-column
            label="定额"
            prop="matQuantity"
            min-width="120"
            show-overflow-tooltip
            align="right"
          >
          </el-table-column>
          <el-table-column
            label="总成物料"
            prop="productionMaterialCode"
            min-width="120"
            show-overflow-tooltip
          >
            <template #default="{ $index, row }">
              {{ row.productionMaterialCode }}-{{ row.productionMaterialName }}
            </template>
          </el-table-column>
          <el-table-column
            label="图号"
            prop="productionFigureNumber"
            min-width="150"
            show-overflow-tooltip
          >
          </el-table-column>

          <el-table-column
            label="成品数量"
            prop="number"
            min-width="120"
            show-overflow-tooltip
            align="right"
          >
          </el-table-column>
        </el-table>
      </div>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <!-- <el-button
          v-if="!props.isReadonly"
          type="primary"
          :loading="loading"
          @click="handleSubmit"
          >确 定</el-button
        > -->
        <el-button @click="closeDialog">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
const dictionaryStore = useDictStoreHook();
import dayjs from "dayjs";
import { useTable, useDownload, useDictionary } from "@/utils/useTable";

defineOptions({
  name: "MESROLLMATERIALCALCULATOREDIT",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  materialIds: {
    type: Array,
    default: () => {
      return [];
    },
  },
  materialId: {
    type: String,
    default: () => {
      return "";
    },
  },
  productionMaterialIds: {
    type: Array,
    default: () => {
      return [];
    },
  },
  number: {
    type: Number,
    default: () => {
      return 0;
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
});

const visibleDialog = ref(false);
const productionMaterialIds = ref([]);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
    console.log("数组", props.productionMaterialIds);
    productionMaterialIds.value = props.productionMaterialIds;
    // console.log(materialIdss.value);
    getMaterial(props.productionMaterialIds, props.materialId);
  }
);

// 根据选择的id进行请求
const getMaterial = async (productionMaterialIds: any, materialId: any) => {
  await request({
    url: "/mes/mesroutingbom/querys",
    method: "post",
    data: {
      materialId,
      productionMaterialIds,
    },
  }).then((res) => {
    if ((res.code = 200)) {
      console.log(res.data);
      tableData.value = res.data;
      tableData.value.forEach((item) => {
        item.numberWeigth = "";
      });
    }
  });
};

const rules = reactive({
  plantId: [{ required: true, message: "请选择工厂", trigger: "change" }],
  materialId: [{ required: true, message: "请选择存货", trigger: "change" }],
  planYear: [{ required: true, message: "请选择计划年", trigger: "change" }],
  planMonth: [{ required: true, message: "请选择计划月份", trigger: "change" }],
  planBatch: [
    { required: true, message: "请输入批次号", trigger: "blur" },
    {
      validator: validateDegree,
      trigger: "blur",
    },
  ],
  planBatchNum: [
    { required: true, message: "请输入批次数量", trigger: "blur" },
    {
      validator: validateDegree,
      trigger: "blur",
    },
  ],
  numberWeigth: [
    {
      validator: validator1,
      trigger: "blur",
    },
  ],
  remarks: [
    { min: 1, max: 255, message: "长度在 1 到 255 个字符", trigger: "blur" },
  ],
});
function validateDegree(rule: any, value: any, callback: (a?: any) => {}) {
  if (isNaN(parseFloat(value)) && isFinite(value)) {
    callback(new Error("请输入数字"));
  } else if (!/^[+-]?\d+?(e[+-]?\d+)?$/.test(value)) {
    callback(new Error("请输入整数"));
  } else {
    callback();
  }
}

function validator1(rule, value, callback: (a?: any) => {}) {
  console.log(value);

  if (!value) {
    //先判断空可以过
    callback(new Error("请输入数字"));
  } else {
    if (/^\d+(\.\d{1,3})?$/.test(value)) {
      //验证正整数和0的正则
      return true;
    } else {
      callback(new Error("请输入数字"));
    }
  }
}

function validateDegree1(rule: any, value: any, callback: (a?: any) => {}) {
  if (isNaN(parseFloat(value)) && isFinite(value)) {
    callback(new Error("请输入数字"));
  } else if (!/^[+-]?\d+?(e[+-]?\d+)?$/.test(value)) {
    callback(new Error("请输入的数字"));
  } else if (Number(value) < 0) {
    callback(new Error("请输入大于0的数字"));
  } else {
    callback();
  }
}

let formData = reactive({
  id: "",
  plantId: "",
  plantCode: "",
  materialId: "",
  materialCode: "",
  materialName: "",
  figureNumber: "",
  planBatch: "",
  planBatchNum: "",
  planFinishQuantity: "",
  planYear: "",
  planMonth: "",
  planState: "0",
  version: "",
  remarks: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  enabled: "",
  deleted: "",
});

watch(
  () => props.data,
  (newVal: any) => {
    formData.id = "";
    if (newVal?.id) {
      const {
        id,
        plantId,
        plantCode,
        materialId,
        materialCode,
        materialName,
        figureNumber,
        planBatch,
        planBatchNum,
        planFinishQuantity,
        planYear,
        planMonth,
        planState,
        version,
        remarks,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        enabled,
        deleted,
      } = newVal;
      Object.assign(formData, {
        id,
        plantId,
        plantCode,
        materialId,
        materialCode,
        materialName,
        figureNumber,
        planBatch,
        planBatchNum,
        planFinishQuantity,
        planYear,
        planMonth,
        planState,
        version,
        remarks,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        enabled,
        deleted,
      });
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
const formRef = ref(ElForm);
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.id = "";
  formData.plantId = "";
  formData.plantCode = "";
  formData.materialId = "";
  formData.materialCode = "";
  formData.materialName = "";
  formData.figureNumber = "";
  formData.planBatch = "";
  formData.planBatchNum = "";
  formData.planFinishQuantity = "";
  formData.planState = "0";
  formData.version = "";
  formData.remarks = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.createdUserName = "";
  formData.lastUpdateTime = "";
  formData.lastUpdatedUserId = "";
  formData.lastUpdatedUserName = "";
  formData.enabled = "";
  formData.deleted = "";
  sum.value = 0;
}
const loading = ref(false);

/** 计划批次保存提交 */
function handleSubmit() {}
onMounted(async () => {});
// 组件销毁时调用
onBeforeUnmount(() => {
  visibleDialog.value = false;
  emit("change-visible", false);
});
const moko = ref([
  {
    id: 1,
    materialCode: "物料编号1",
    figureNumber: "图号1",
    weigth: "",
    number: "123",
  },
]);
const tableData = ref([]);
let sum = ref(0);
const countSubmit = async () => {
  tableData.value.forEach((item) => {
    item.number = (item.numberWeigth / item.matQuantity).toFixed(2);
    sum.value += Number(item.numberWeigth);
  });
};
</script>
<style scoped lang="scss">
.formTable {
  :deep(.el-form-item) {
    margin-right: 0 !important;
  }
  :deep(.el-scrollbar__wrap) {
    max-height: 290px;
    overflow-y: auto;
  }
  :deep(.el-table .el-form-item) {
    padding: 11px 0 0 0 !important;
  }
  :deep(.el-table .el-form-item__error) {
    font-size: 11px !important;
  }

  :deep(.el-table) {
    // .cell.el-tooltip {
    //   padding: 0 15px;
    // }

    // .el-table__body td.el-table__cell {
    //   padding: 20;
    // }
    // .cell.el-tooltip {
    //   padding: 5px;
    // }
    .el-table__body td.el-table__cell {
      // padding: 10px !important;
      padding: 0 !important;
    }
  }
}

.formTable {
  :deep(.el-form-item) {
    margin: 0 0 13px 0 !important;
    width: 100%;
  }
}
</style>
